//app.js
App({
  // 链接地址
  clientUrl: 'https://weixin.aiuplus.com/gzlx/f/wxApp',
  // 测试地址
  // clientUrl: 'http://120.76.101.253/gzlx/f/wxApp',

  openId: null,
  globalData: {
    // 预约车
    map: {
      // 我的位置
      startAddress: '我的位置',
      endAddress: '目的地',
      strLatitude: '',
      strLongitude: '',
      endLatitude: '',
      endLongitude: '',
    },
    //时间属性
    nowYear: '',
    nowDate: '',
    nowMonth: '',
    nowDay: '',
    nowHours: '',
    nowMinutes: '',
    nowSeconds: '',
    nowDate2: '',

    //时间选择器
    dateArr: [
      // {
      //   value: '2018-11-17 10:29#23:59'
      // }
    ],
    startDate: [],
    endDate: [],

    // 用户信息
    userInfo: {},
    // 系统在线时间
    newmeetingDate: [],
    // 共享车在线时间
    shareCarMeetingDate: [],
    meetingDate: '',
    // strServer: '',
    // endServer: '',
    //客服号码
    meetiongPhone: '', //网约车客服
    shareCarmeetiongPhone: '', //网约车客服
  },
  onLaunch: function () {
    var that = this;

    //验证登录，如果当前全局没有值，读取setStrong，如果还没有，就去登录页面
    //that.userLogin();


    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    //获取当前时间戳
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    //console.log("当前时间戳为：" + timestamp);

    //获取当前时间
    var n = timestamp * 1000;
    var date = new Date(n);
    this.globalData.nowDate = new Date(n);
    this.globalData.nowYear = date.getFullYear();
    this.globalData.nowMonth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    this.globalData.nowDay = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    this.globalData.nowHours = date.getHours();
    this.globalData.nowMinutes = date.getMinutes();
    this.globalData.nowSeconds = date.getSeconds();
    this.globalData.nowDate2 = this.globalData.nowYear + '-' + this.globalData.nowMonth + '-' + this.globalData.nowDay + ' ' + this.globalData.nowHours + ":" + this.globalData.nowMinutes

    //------login--------
    wx.login({
      success: res => {
        var that = this;
        console.log("--登录中--", res);
        //发送 res.code 到后台换取 openId, sessionKey, unionId1
        if (res.code) {
          const params = {
            code: res.code,
          };
          // 发送请求
          that.request({
            url: "/code2OpenId",
            data: params,
            success: function (res) {
              //console.log('code2OpenId---', res);
              const data = res.data.data;
              that.openId = data.openid;
            }
          })
        } else {
          console.log('获取用户登录状态失败！' + res.errMsg)
        }
      },
      fail(res) {
        console.log('------登录失败 fail-------')
        console.log(res)
        wx.hideLoading();
      }
    })

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
    // 请求初始数据
    that.request({
      url: "/getInitData",
      success: (res) => {
        console.log('初始化数据加载', res.data)
        that.globalData.meetingDate = res.data.data.meetingDate;
        that.globalData.meetiongPhone = res.data.data.meetiong_phone;
        that.globalData.shareCarmeetiongPhone = res.data.data.shareCarmeetiong_phone;
        that.globalData.newmeetingDate = res.data.data.newmeetingDate;
        that.globalData.shareCarMeetingDate = res.data.data.shareCarMeetingDate;
        // that.globalData.newmeetingDate = [];
        // that.globalData.dateArr = res.data.data.newmeetingDate
      }
    })
  },
  // ajax封装
  request: function (params) {
    const that = this;
    var host = that.clientUrl;
    console.log("发起请求：" + host + params.url, params);
    wx.request({
      url: host + params.url,
      data: params.data || null,
      method: params.method || 'GET',
      success: function (res) {
        //console.log(res)
        if (res.data && res.statusCode != 200 || res.data.code == 0) {
          console.log('---请求失败（success）---:', res.data);
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 3000
          })
        } else if (typeof params.success == "function") {
          params.success(res);
        }
      },
      fail: function () {
        console.warn('---请求失败（fail）---:' + host + params.url);
        if (typeof params.fail == "function") {
          params.fail();
        }
      },
      complete: function (res) {
        console.log("请求完成：" + host + params.url, params, res);
        if (typeof params.complete == "function") {
          params.complete();
        }
      }
    });
  },
  // userLogin: function() {
  //   var that = this;
  //   if (JSON.stringify(that.globalData.userInfo) == "{}") {
  //     wx.getStorage({
  //       key: 'users',
  //       success: function(e) {
  //         //console.log('e--',e)
  //         if (JSON.stringify(e.data) != "") {
  //           that.globalData.userInfo = e.data;
  //           wx.showLoading({
  //             title: '自动登录中',
  //           })
  //           setTimeout(function() {
  //             wx.hideLoading()
  //             wx.reLaunch({
  //               url: '../index/index'
  //             })
  //           }, 1000)
  //         } else {
  //           console.log('e', e)
  //           wx.reLaunch({
  //             url: '../user/user'
  //           })
  //         }
  //       }
  //     })
  //   }
  // },
  // noServerTime: function() {
  //   var nowdate = this.globalData.nowDate
  //   var startdate = this.globalData.meetingDate[0].value
  //   var enddate = this.globalData.meetingDate[1].value
  //   // var startdate = '2018-11-15'
  //   // var enddate = '2018-11-20'
  //   var startD = new Date(startdate).getTime();
  //   var endD = new Date(enddate).getTime();
  //   var nowD = new Date(nowdate).getTime();

  //   if (nowD >= startD && nowD <= endD) {
  //     console.log('通过')
  //     return true
  //   } else {
  //     wx.showToast({
  //       title: '不在服务时间内',
  //       icon: 'none',
  //       duration: 2000,
  //       mask: true,
  //     })
  //     console.log('不通过')
  //     return false
  //   }
  // },
  // noServerHour: function() {
  //   var nHour = this.globalData.nowHours
  //   var sHour = this.globalData.strServer
  //   var eHour = this.globalData.endServer
  //   // var sHour = '10'
  //   // var eHour = '21'
  //   // 
  //   if (nHour >= sHour && nHour < eHour) {
  //     console.log('通过')
  //     console.log('nHour', nHour, sHour, eHour)
  //     return true
  //   } else {
  //     wx.showToast({
  //       title: '不在服务时间内',
  //       icon: 'none',
  //       duration: 2000,
  //       mask: true,
  //     })
  //     console.log('不通过')
  //     console.log('nHour', nHour, sHour, eHour)
  //     return false
  //   }
  // },
  onShareAppMessage: function () {
    return {
      title: '广丰出行',
      path: '/page/user/user',
      success: function (res) {

      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})